package com.ms.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

@SuppressWarnings("rawtypes")
public class AjaxOut {
	
	private static Logger logger = Logger.getLogger(AjaxOut.class);
 
	/**
	 * AJAX输出页面
	 * 
	 * @param response
	 * @param s
	 */
	public static void responseText(HttpServletResponse response, String s) {
		// 指定内容类型
		response.setContentType("text/html;charset=utf-8");
		// 禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			PrintWriter out = response.getWriter();
			out.print(s);
			out.close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static void responseXml(HttpServletResponse response, String s) {
		// 指定内容类型
		response.setContentType("text/xml;charset=utf-8");
		// 禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			PrintWriter out = response.getWriter();
			out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			out.print(s);
			out.close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static String getThrowableTrace(Throwable throwable) {
		try {
			StringBuffer errorBuf = new StringBuffer();
			StackTraceElement[] trace = throwable.getStackTrace();
			for (int i = 0; i < trace.length; i++) {
				errorBuf.append("  at " + trace[i] + "\n");
			}
			return errorBuf.toString();
		}
		catch (Exception e) {
			logger.error(e.getMessage(), e);
			return "";
		}
	}

	/**
	 * 将错误信息输出到页面
	 * 
	 * @param response
	 * @param info 信息
	 * @param cl 错误类
	 * @param throwable
	 */
	public static void responseException(HttpServletResponse response, String info, Class cl, Throwable throwable) {
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			StringBuffer errorBuf = new StringBuffer();
			errorBuf.append("<table>");
			errorBuf.append("<tr>");
			errorBuf.append("<td>");
			errorBuf.append(info + ": " + cl);
			errorBuf.append("</td>");
			errorBuf.append("</tr>");

			errorBuf.append("<tr>");
			errorBuf.append("<td>");
			errorBuf.append(throwable.getClass() + ": " + throwable.getMessage());
			errorBuf.append("</td>");
			errorBuf.append("</tr>");

			StackTraceElement[] trace = throwable.getStackTrace();
			for (int i = 0; i < trace.length; i++) {
				errorBuf.append("<tr>");

				if (trace[i].toString().contains(cl.getName()))
					errorBuf.append("<td bgcolor='#FF0000'>");
				else
					errorBuf.append("<td>");

				errorBuf.append("&nbsp;&nbsp;at " + trace[i]);
				errorBuf.append("</td>");
				errorBuf.append("</tr>");
			}

			Throwable ourCause = throwable.getCause();
			if (ourCause != null) {
				errorBuf.append("<tr>");
				errorBuf.append("<td>");
				errorBuf.append(ourCause);
				errorBuf.append("</td>");
				errorBuf.append("</tr>");
			}
			errorBuf.append("</table>");

			PrintWriter out = response.getWriter();
			out.print(errorBuf);

			out.close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static String getExceptionMessage(Throwable throwable) {
		StringBuffer errorBuf = new StringBuffer();
		StackTraceElement[] trace = throwable.getStackTrace();
		for (int i = 0; i < trace.length; i++) {
			 errorBuf.append("\n\tat " + trace[i]);
		}

		Throwable ourCause = throwable.getCause();
		if (ourCause != null) {
			errorBuf.append("\n\tat " + getExceptionMessage(ourCause));
		}
		
		return errorBuf.toString();
	}

	/**
	 * 将JSon格式的grid输出到页面<br>
	 * 如果在grid中有特殊要求，如链接等，则需要自己重新实现该方法，不可先遍历dataList再调用该方法
	 * 
	 * @param response
	 * @param displayDataList 显示的列表
	 * @param recordsCount Grid的总记录数
	 */
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList, int totalCount, SimpleDateFormat df) {
		try {
			JSONObject dataObj = new JSONObject();
			dataObj.put("total", totalCount);
			JSONArray dataArray = new JSONArray();
			for (int i = 0; i < displayDataList.size(); i++) {
				JSONObject obj = JSONObject.fromObject(EntityReflect.getObjectJSonString(displayDataList.get(i), df));
				dataArray.add(obj);
			}
			dataObj.put("invdata", dataArray);
			AjaxOut.responseText(response, dataObj.toString());
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 返回前台列表
	 * @param response
	 * @param displayDataList 数据列表
	 * @param df 时间格式
	 * @param otherInfo 其它信息
	 */
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList, SimpleDateFormat df, String otherInfo) {
		int totalCount = displayDataList == null ? 0 : displayDataList.size();
		responseJSonGrid(response, displayDataList, totalCount, df, otherInfo);
	}
	
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList, SimpleDateFormat df) {
		int totalCount = displayDataList == null ? 0 : displayDataList.size();
		responseJSonGrid(response, displayDataList, totalCount, df, "");
	}
	
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList) {
		int totalCount = displayDataList == null ? 0 : displayDataList.size();
		responseJSonGrid(response, displayDataList, totalCount, "");
	}
	
	/**
	 * 返回前台列表
	 * @param response
	 * @param displayDataList 数据列表
	 * @param otherInfo 其它信息
	 */
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList, String otherInfo) {
		int totalCount = displayDataList == null ? 0 : displayDataList.size();
		responseJSonGrid(response, displayDataList, totalCount, otherInfo);
	}
	
	/**
	 * 返回前台列表
	 * @param response
	 * @param displayDataList 数据列表
	 * @param totalCount 总记录数, 分页查询到记录总数！
	 * @param df 时间格式 
	 * @param otherInfo 其它信息
	 */
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList, int totalCount, SimpleDateFormat df, String otherInfo) {
		try {
			JSONObject dataObj = new JSONObject();
			dataObj.put("total", totalCount);
			dataObj.put("otherInfo", otherInfo);
			JSONArray dataArray = new JSONArray();
			
			if(displayDataList != null) {
				for (int i = 0; i < displayDataList.size(); i++) {
					JSONObject obj = JSONObject.fromObject(EntityReflect.getObjectJSonString(displayDataList.get(i), df));
					dataArray.add(obj);
				}
			}
			
			dataObj.put("invdata", dataArray);
			AjaxOut.responseText(response, dataObj.toString());
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList, int totalCount) {
		try {
			JSONObject dataObj = new JSONObject();
			dataObj.put("total", totalCount);
			JSONArray dataArray = new JSONArray();
			dataArray.addAll(displayDataList);
			dataObj.put("invdata", dataArray);
			AjaxOut.responseText(response, dataObj.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 返回前台列表<br>
	 * @param response
	 * @param displayDataList  数据列表
	 * @param totalCount 总记录数, 分页查询到记录总数！
	 * @param otherInfo 其它信息
	 */
	public static void responseJSonGrid(HttpServletResponse response, List displayDataList, int totalCount, String otherInfo) {
		try {
			JSONObject dataObj = new JSONObject();
			dataObj.put("total", totalCount);
			dataObj.put("otherInfo", otherInfo);
			JSONArray dataArray = new JSONArray();
			dataArray.addAll(displayDataList);
			dataObj.put("invdata", dataArray);
			AjaxOut.responseText(response, dataObj.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 将JSon格式的grid输出到页面<br>
	 * @param response
	 * @param　jsonArray　现成的json数组
	 */
	public static void responseJSonGrid(HttpServletResponse response,JSONArray jsonArray) {
		try {
			JSONObject dataObj = new JSONObject();
			dataObj.put("invdata", jsonArray);
			AjaxOut.responseText(response, dataObj.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 将JSON数据传到页面供JQGrid使用
	 * @param response
	 * @param list
	 * @param count
	 * @param simpleDateFormat
	 */
	public static void responseJSonDataForJQGrid(HttpServletResponse response, List list, int count, JQGridLimit jqLimit, SimpleDateFormat simpleDateFormat) {
		try {
			JSONObject dataObj = new JSONObject();
			dataObj.put("page", jqLimit.getPage());
			dataObj.put("total", jqLimit.getTotalPageCount());
			dataObj.put("records", count);
			JSONArray dataArray = new JSONArray();
			for (int i = 0; i < list.size(); i++) {
				dataArray.add(list.get(i));
			}
			dataObj.put("invdata", dataArray);
			AjaxOut.responseText(response, dataObj.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}
